import docker
from docker.errors import APIError

from application.celery import app
from celery.utils.serialization import jsonify
from time import sleep


# 导入Celery库
from celery import Celery
# 创建Celery实例
# app = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/1')

@app.task
def start_container():
    print("调试开始")
    sleep(10)
    send_message_to_frontend.delay("123")
    print("调用结束")
    # 使用docker客户端创建一个容器
    # client = Client(base_url='unix://var/run/docker.sock')
    # print("ssssssssssssssssssssssssssssssss")
    # client = docker.from_env()
    # command_text = 'python classify/predict.py' + \
    #                ' --source ' + 'runs/classify6e5a0e85-b4a0-485f-be54-a758115317e3/test/test.jpg' + \
    #                ' --project ' + 'runs/classify6e5a0e85-b4a0-485f-be54-a758115317e3/test' + \
    #                ' --weights ' + 'runs/classify6e5a0e85-b4a0-485f-be54-a758115317e3/train/exp/weights/best.pt'
    # client.containers.run('ultralytics/yolov5',
    #                       name='classify6e5a0e85-b4a0-485f-be54-a758115317e3',
    #                       volumes={
    #                           '/c/Users/14798/docker/test': {'bind': '/usr/src/app', 'mode': 'rw'}},
    #                       detach=True, remove=True, tty=True,
    #                       command=command_text)
    # # container = client.create_container(image=image, command='nginx -g "daemon off;"')
    # # client.start(container=container.get('Id'))
    # monitor_container_status.delay()

@app.task
def stop_container(container_name):
    # 暂停容器
    try:
        client = docker.from_env()
        container = client.containers.get(container_name)
        if container:
            container.stop()
    except APIError as e:
        print(f"Failed to stop container: {e}")
    # client = docker.from_env()
    # for container in client.containers.list():
    #     if container.name == container_name:
    #         container.stop()

@app.task
def send_message_to_frontend(message):
    # 使用Django的HttpResponse对象返回消息
    # response = HttpResponse(message)
    # 返回消息到前端

    return jsonify(message)

@app.task
def monitor_container_status():
    # 监听docker API的消息
    # client = Client(base_url='unix://var/run/docker.sock')
    client = docker.from_env()
    for line in client.events(decode=True):
        print("1111111111111111111")
        print(line)
        if 'status' in line and line['status'] == 'die':
            # 发送消息给前端
            send_message_to_frontend.delay(line)